package com.yelin.taketitle

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.yalantis.ucrop.UCrop
import kotlinx.android.synthetic.main.activity_draw_rect.*
import java.io.File
import java.io.FileInputStream
import java.text.SimpleDateFormat
import java.util.*


class DrawRectActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_draw_rect)

        val fs = FileInputStream("/sdcard/test.png");

        val bitmap = BitmapFactory.decodeStream(fs)

        val imageUri =
            Uri.parse(MediaStore.Images.Media.insertImage(contentResolver, bitmap, null, null))

        val destinationUri: Uri =  Uri.parse("file://" + getFileName())

        btn_crop.setOnClickListener {
            UCrop.of(imageUri, destinationUri)
                .withAspectRatio(16f, 9f)
                .withMaxResultSize(800, 640)
                .start(this)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && requestCode == UCrop.REQUEST_CROP) {
            val resultUri: Uri? = data?.let { UCrop.getOutput(it) }
        } else if (resultCode == UCrop.RESULT_ERROR) {
            val cropError = data?.let { UCrop.getError(it) }
        }
    }


    /**
     * 生成文件路径和文件名
     *
     * @return
     */
    @SuppressLint("SimpleDateFormat")
    private fun getFileName(): String? {
        val saveDir =
            Environment.getExternalStorageDirectory().toString() + "/testquestions"
        val dir = File(saveDir)
        if (!dir.exists()) {
            val isSuccess = dir.mkdirs()
            if (isSuccess) {
                Toast.makeText(
                    this@DrawRectActivity,
                    "文件夹创建成功",
                    Toast.LENGTH_LONG
                ).show()
            } else {
                Toast.makeText(
                    this@DrawRectActivity,
                    "文件夹创建失败",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
        // 用日期作为文件名，确保唯一性
        val date = Date()
        val formatter =
            SimpleDateFormat("yyyy-MM-dd_HH-mm-ss")
        return saveDir + "/" + formatter.format(date) + ".png"
    }
}
